package com.wthink.hzgj.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.flexbox.FlexboxLayoutManager
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.R
import com.wthink.hzgj.databinding.FragmentHomeBinding
import com.wthink.hzgj.home.adapter.LineAdapter
import com.wthink.hzgj.home.data.Line
import com.wthink.hzgj.home.viewmodel.HomeViewModel
import com.wthink.hzgj.util.adapter.OnItemClickListener
import com.wthink.hzgj.util.closeDefaultAnimator
import com.wthink.hzgj.util.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class HomeFragment : Fragment() {

    private val viewModel by viewModels<HomeViewModel>()

    private lateinit var binding: FragmentHomeBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_home,
            container,
            false
        )
        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        binding.lineListView.layoutManager = FlexboxLayoutManager(context)
        binding.lineListView.adapter = LineAdapter().apply {
            mItemClickListener = object : OnItemClickListener {
                override fun onItemClick(obj: Any, position: Int) {
                    viewModel.selectLine((obj as Line).id)
                }
            }
        }

        closeDefaultAnimator(binding.lineListView)

        binding.reqLine.setOnClickListener { view ->
            viewModel.reqLine()
        }

        binding.viewStation.setOnClickListener { view ->
            viewModel.getSelectLine1()?.let { line ->
                val args = Bundle()
                args.putString("lineId", line.id)
                args.putString("lineName", line.name)
                view.findNavController().navigate(R.id.stationFragment, args)
            }
        }

        binding.prev.setOnClickListener {
            viewModel.loadPrev()
        }

        binding.next.setOnClickListener {
            viewModel.loadNext()
        }

        viewModel.start()
    }
}
